<template>
  <!--修改密码界面-->
  <el-dialog title="修改密码" width="40%" :visible.sync="dialogVisible" :close-on-click-modal="false">
    <el-form :model="dataForm" :rules="dataFormRules" ref="dataForm" :size="size" label-width="120px" label-position="right">
      <el-form-item label="原密码" prop="password">
        <el-input v-model="dataForm.password" type="password" auto-complete="off" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="dataForm.newPassword" type="password" auto-complete="off" />
      </el-form-item>
      <el-form-item label="重复新密码" prop="checkNewPassword">
        <el-input v-model="dataForm.checkNewPassword" type="password" auto-complete="off" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :size="size" @click.native="dialogVisible = false">取消</el-button>
      <el-button :size="size" type="primary" @click.native="handleModifyPassword">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'ModifyPasswordDialog',
  props: {
    size: { type: String, default: 'mini' }
  },
  data () {
    return {
      dialogVisible: false,
      dataForm: {
        password: '',
        newPassword: '',
        checkNewPassword: ''
      },
      dataFormRules: {
        password: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' }
        ],
        checkNewPassword: [
          {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请再次输入新密码'))
              } else if (value !== this.dataForm.newPassword) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            }
          }
        ]
      }
    }
  },
  methods: {
    // 设置可见性
    setDialogVisible (visible) {
      this.dialogVisible = visible
    },
    // 修改密码
    handleModifyPassword () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          let params = {
            id: this.$store.state.app.user.id,
            password: this.dataForm.password,
            newPassword: this.dataForm.newPassword
          }
          this.$api.app.modifyPassword(params).then((res) => {
            if (res.code === 0) {
              this.$message({ message: '修改密码成功', type: 'success' })
              this.dialogVisible = false
            } else {
              this.$message({ message: '操作失败, ' + res.message, type: 'error' })
            }
          })
        }
      })
    }
  }
}
</script>
